package logic

import (
	"context"
	"errors"
	"user/model"

	"user/internal/svc"
	"user/rpc/user"

	"github.com/zeromicro/go-zero/core/logx"
	"golang.org/x/crypto/bcrypt"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// Register 注册
func (l *RegisterLogic) Register(in *user.RegisterRequest) (*user.RegisterResponse, error) {
	//先查询当前用户名是否已经存在库里
	_, err := l.svcCtx.UsersModel.FindOneByUsername(l.ctx, in.Username)
	if err != nil {
		//用户不存在说明可以继续往下走
		if errors.Is(err, model.ErrNotFound) {
			//创建用户
			password, _ := bcrypt.GenerateFromPassword([]byte(in.Password), bcrypt.DefaultCost)
			_, err := l.svcCtx.UsersModel.Insert(l.ctx, &model.Users{
				Username: in.Username,
				Password: string(password),
			})
			if err != nil {
				return nil, err
			}
			return &user.RegisterResponse{}, nil
		}
		return nil, errors.New("用户已经存在")
	}
	return nil, err
}
